<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use think\Cache;
use think\Db;

class Index extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = 'default';

    public function index()
    {

        $index_index_data = Cache::get('index_index_data');
        if($index_index_data){
            $banner = $index_index_data['banner'];
            $index_banner = $index_index_data['index_banner'];

        }else{
            $banner = Db::name('banner')
                ->field('image,url')
                ->where('status',0)
                ->order(['sort'=>"asc",'id'=>'asc'])
                ->select();
            $index_banner = Db::name('indeximg')
                ->field('image,name,sub_name,rules')
                ->where('status',0)
                ->order(['sort'=>"asc",'id'=>'asc'])
                ->select();
            foreach ($banner as $k=>&$v){

                // $v['image'] = cdnurl($v['image'], true);
                $v['image'] = config('http_url').$v['image'];
            }
            foreach ($index_banner as $k=>&$v){

                // $v['image'] = cdnurl($v['image'], true);
                $v['image'] = $v['image']?config('http_url').$v['image']:"";
            }

            $data =[
                'banner'=>$banner,
                'index_banner'=>$index_banner,
            ];
            Cache::set('index_index_data',$data,600);
        }

        $this->view->assign("banner", $banner);
        $this->view->assign("index_banner", $index_banner);
        $this->view->assign("acName", 'index');

        return $this->view->fetch();
    }

    /* public function cate($name,$id=''){

         $dir = ROOT_PATH . 'application/index/view/index/'.$name.'.html';
         // 使用file_exists
         if (!file_exists($dir)) {
             $content = '<div>
                 <img src="{$image}" alt="">
             </div>
 ';
             // 打开文件（如果不存在则创建）并写入内容
             if (!file_put_contents($dir, $content) !== false) {
                 exit('创建文件失败');
             }
         }

         $image = '';

         if(!empty($id)){
             $map['id'] = ['=',$id];

         }else{
             $map['rules'] = ['=',$name];
         }
         $info = Db::name('cate')
             ->where($map)
             ->find();
         $image = $info?$info['image']:"";
         $subName = $info?$info['sub_name']:"";
         $content1 = $info?$info['content1']:"";
         $content2 = $info?$info['content2']:"";
         $content3 = $info?$info['content3']:"";
         $content4 = $info?$info['content4']:"";
         $content5 = $info?$info['content5']:"";
         $content6 = $info?$info['content6']:"";

         if(empty($image) || empty($subName)){
             $indexInfo = Db::name('indeximg')
                 ->where($map)->find();
             $image = $indexInfo?$indexInfo['cimage']:"";
             $subName = $indexInfo?$indexInfo['name']:"";

             $content1 = $indexInfo?$indexInfo['content1']:"";
             $content2 = $indexInfo?$indexInfo['content2']:"";
             $content3 = $indexInfo?$indexInfo['content3']:"";
             $content4 = $indexInfo?$indexInfo['content4']:"";
             $content5 = $indexInfo?$indexInfo['content5']:"";
             $content6 = $indexInfo?$indexInfo['content6']:"";
         }


         $image = $image?config('http_url').$image:"";
         $this->view->assign("image", $image);
         $this->view->assign("acName", $name);
         $this->view->assign("subName", $subName);
         $this->view->assign("id", $id);
         $this->view->assign("content1",$content1);
         $this->view->assign("content2",$content2);
         $this->view->assign("content3",$content3);
         $this->view->assign("content4",$content4);
         $this->view->assign("content5",$content5);
         $this->view->assign("content6",$content6);

         return $this->view->fetch($name);

     }*/

    public function cate($name, $id = '')
    {

        $cacheKey = "cate_{$name}_{$id}";
        $data = Cache::get($cacheKey);

        if (!$data) {
            $map = [];
            if (!empty($id)) {
                $map['id'] = $id;
            } else {
                $map['rules'] = $name;
            }

            // 只查需要的字段
            $fields = 'image,sub_name,content1,content2,content3,content4,content5,content6';
            $info = Db::name('cate')->field($fields)->where($map)->find();

            if ($info && !empty($info['image']) && !empty($info['sub_name'])) {
                $data = $info;
            } else {
                $indexInfo = Db::name('indeximg')->field('cimage as image,name as sub_name,content1,content2,content3,content4,content5,content6')->where($map)->find();
                $data = $indexInfo ?: [];
            }

            // 处理图片路径
            if (!empty($data['image'])) {
                $data['image'] = config('http_url') . $data['image'];
            }

            Cache::set($cacheKey, $data, 600); // 缓存10分钟
        }

        // 视图文件建议用通用模板
        $viewFile = ROOT_PATH . 'application/index/view/index/' . $name . '.html';
        if (!file_exists($viewFile)) {
            $content = '<div><img src="{$image}" alt=""></div>';
            file_put_contents($viewFile, $content);
        }


        $this->view->assign("image", $data['image'] ?? '');
        $this->view->assign("acName", $name);
        $this->view->assign("subName", $data['sub_name'] ?? '');
        $this->view->assign("id", $id);
        for ($i = 1; $i <= 6; $i++) {
            $this->view->assign("content$i", $data["content$i"] ?? '');
        }

        if($name=='sqlt'){
            $this->redirect(url('index/lt_list'));
        }
        return $this->view->fetch($name);
    }

    /**
     * 前台获取视频分类（根据栏目 cate_id）
     */
    public function videocates()
    {
        $cateId = (int)$this->request->get('cate_id', 0);
        if ($cateId <= 0) {
            return json(['code' => 0, 'msg' => 'cate_id required', 'data' => []]);
        }
        $list = Db::name('vcate')
            ->field('id,title,sort')
            ->where('cate_id', '=', $cateId)
            ->order(['sort' => 'asc', 'id' => 'asc'])
            ->select();
        return json(['code' => 1, 'data' => $list]);
    }

    /**
     * 前台获取视频列表（根据栏目 cate_id，可选 vcate_id）含分页
     */
    public function videolist()
    {
        $cateId = (int)$this->request->get('cate_id', 0);
        $vcateId = (int)$this->request->get('vcate_id', 0);
        $page = max(1, (int)$this->request->get('page', 1));
        $limit = max(1, min(60, (int)$this->request->get('limit', 12)));

        if ($cateId <= 0) {
            return json(['code' => 0, 'msg' => 'cate_id required', 'data' => []]);
        }

        $map = [];
        if ($vcateId > 0) {
            $map['vcate_id'] = $vcateId;
        }

        $total = Db::name('video')->where($map)->where('cate_id', '=', $cateId)->count();

        $list = [];
        if ($total > 0) {
            $list =  Db::name('video')->where($map)->where('cate_id', '=', $cateId)
                ->field('id,title,vcate_id,cate_id,sort,image,ifarme,createtime')
                ->order(['sort' => 'asc', 'id' => 'desc'])
                ->page($page, $limit)
                ->select();
            // 处理图片绝对路径
            foreach ($list as &$row) {
                if (!empty($row['image']) && strpos($row['image'], 'http') !== 0) {
                    $row['image'] = config('http_url') . $row['image'];
                }
            }
            unset($row);
        }

        return json([
            'code' => 1,
            'data' => [
                'total' => $total,
                'list' => $list,
                'page' => $page,
                'limit' => $limit,
                'pages' => (int)ceil($total / $limit ?: 1)
            ]
        ]);
    }

    public function lt_list()
    {
        try {
            $fields = 'image,sub_name,content1,content2,content3,content4,content5,content6';
            $map = [];
            $name = 'sqlt';
            $map['rules'] = $name;
            $id = '23';
            $data = Db::name('cate')->field($fields)->where($map)->find();
            if (!empty($data['image'])) {
                $data['image'] = config('http_url') . $data['image'];
            }
        } catch (\Exception $e) {
            // 数据库连接失败，返回默认数据
            $data = ['image' => '', 'sub_name' => '论坛列表'];
        }

        // 获取搜索参数
        $keyword = input('keyword', '');
        $ltcateId = input('ltcate_id', 0);

        // 构建文章查询条件
        $articleQuery = Db::name('lt');
        if (!empty($keyword)) {
            $articleQuery->where('title|content', 'like', '%' . $keyword . '%');
        }
        if ($ltcateId > 0) {
            $articleQuery->where('ltcate_id', $ltcateId);
        }

        // 获取有文章的分类列表（根据搜索结果动态显示）
        $cateList = [];
        try {
            if (!empty($keyword)) {
                // 搜索模式下，只显示有搜索结果的分类
                $cateQuery = Db::name('lt');
                $cateQuery->where('title|content', 'like', '%' . $keyword . '%');
                if ($ltcateId > 0) {
                    $cateQuery->where('ltcate_id', $ltcateId);
                }
                $cateIds = $cateQuery->column('ltcate_id');
                if (!empty($cateIds)) {
                    $cateList = Db::name('ltcate')
                        ->field('id,title,sort')
                        ->where('id', 'in', array_unique($cateIds))
                        ->order(['sort' => 'asc', 'id' => 'asc'])
                        ->select();
                }
            } else {
                // 非搜索模式下，显示所有分类
                $cateList = Db::name('ltcate')
                    ->field('id,title,sort')
                    ->order(['sort' => 'asc', 'id' => 'asc'])
                    ->select();
            }
        } catch (\Exception $e) {
            // 数据库连接失败，返回空分类列表
            $cateList = [];
        }

        // 获取置顶文章
        $topList = [];
        try {
            $topQuery = Db::name('lt');
            if (!empty($keyword)) {
                $topQuery->where('title|content', 'like', '%' . $keyword . '%');
            }
            if ($ltcateId > 0) {
                $topQuery->where('ltcate_id', $ltcateId);
            }
            $topList = $topQuery
                ->where('is_top', 1)
                ->field('id,title,content,view,ltcate_id,createtime')
                ->order(['id' => 'desc'])
                ->limit(5)
                ->select();
        } catch (\Exception $e) {
            // 数据库连接失败，返回空列表
            $topList = [];
        }

        // 获取普通文章列表
        $normalList = [];
        try {
            $normalQuery = Db::name('lt');
            if (!empty($keyword)) {
                $normalQuery->where('title|content', 'like', '%' . $keyword . '%');
            }
            if ($ltcateId > 0) {
                $normalQuery->where('ltcate_id', $ltcateId);
            }
            $normalList = $normalQuery
                ->where('is_top', 0)
                ->field('id,title,content,view,ltcate_id,createtime')
                ->order(['id' => 'desc'])
              ->paginate(1,false,['query' => request()->param()]);
        } catch (\Exception $e) {
            // 数据库连接失败，返回空列表
            $normalList = [];
        }

        // 处理文章内容截取
        foreach ($topList as &$item) {
            $item['content'] = mb_substr(strip_tags($item['content']), 0, 100) . '...';
            $item['createtime'] = date('Y-m-d H:i:s', $item['createtime']);
        }
        foreach ($normalList as &$item) {
            $item['content'] = mb_substr(strip_tags($item['content']), 0, 100) . '...';
            $item['createtime'] = date('Y-m-d H:i:s', $item['createtime']);
        }

        $this->view->assign("image", $data['image'] ?? '');
        $this->view->assign("acName", $name);
        $this->view->assign("subName", $data['sub_name'] ?? '');
        $this->view->assign("id", $id);
        $this->view->assign("cateList", $cateList);
        $this->view->assign("topList", $topList);
        $this->view->assign("normalList", $normalList);
        $this->view->assign("currentCateId", $ltcateId);
        $this->view->assign("keyword", $keyword); // 传递搜索关键词到模板


        return $this->view->fetch();
    }
    public function lt_detail()
    {
        $id = input('id');
        if (empty($id)) {
            $this->error('参数错误');
        }

        // 获取文章详情
        $detail = Db::name('lt')
            ->alias('l')
            ->join('ltcate c', 'l.ltcate_id = c.id', 'LEFT')
            ->field('l.id,l.title,l.content,l.view,l.ltcate_id,l.createtime,l.updatetime,c.title as cate_title')
            ->where('l.id', $id)
            ->find();

        if (empty($detail)) {
            $this->error('文章不存在');
        }

        // 增加浏览量
        Db::name('lt')->where('id', $id)->setInc('view');

        // 格式化时间
        $detail['createtime'] = date('Y-m-d H:i:s', $detail['createtime']);
        $detail['updatetime'] = date('Y-m-d H:i:s', $detail['updatetime']);

        // 获取相关文章（同分类的其他文章）
        $relatedList = Db::name('lt')
            ->field('id,title,view,createtime')
            ->where('ltcate_id', $detail['ltcate_id'])
            ->where('id', '<>', $id)
            ->order(['id' => 'desc'])
            ->limit(5)
            ->select();

        foreach ($relatedList as &$item) {
            $item['createtime'] = date('Y-m-d H:i:s', $item['createtime']);
        }

        $map = [];
        $fields = 'image,sub_name,content1,content2,content3,content4,content5,content6';
        $name = 'sqlt';
        $map['rules'] = $name;
        $id = '23';
        $data = Db::name('cate')->field($fields)->where($map)->find();
        if (!empty($data['image'])) {
            $data['image'] = config('http_url') . $data['image'];
        }
        $this->view->assign("image", $data['image'] ?? '');
        $this->view->assign("acName", $name);
        $this->view->assign("subName", $data['sub_name'] ?? '');
        $this->view->assign("detail", $detail);
        $this->view->assign("relatedList", $relatedList);

        return $this->view->fetch();
    }

    /**
     * 获取论坛分类列表API
     */
    public function lt_cates()
    {
        $list = Db::name('ltcate')
            ->field('id,title,sort')
            ->order(['sort' => 'asc', 'id' => 'asc'])
            ->select();
        return json(['code' => 1, 'data' => $list]);
    }

    /**
     * 获取论坛文章列表API
     */
    public function lt_list_api()
    {
        $ltcateId = (int)$this->request->get('ltcate_id', 0);
        $keyword = $this->request->get('keyword', '');
        $page = max(1, (int)$this->request->get('page', 1));
        $limit = max(1, min(50, (int)$this->request->get('pageSize', 10)));

        $query = Db::name('lt')
            ->alias('l')
            ->join('ltcate c', 'l.ltcate_id = c.id', 'LEFT')
            ->field('l.id,l.title,l.content,l.view,l.ltcate_id,l.is_top,l.createtime,c.title as cate_title');

        // 分类筛选
        if ($ltcateId > 0) {
            $query->where('l.ltcate_id', $ltcateId);
        }

        // 关键词搜索
        if (!empty($keyword)) {
            $query->where('l.title|l.content', 'like', '%' . $keyword . '%');
        }

        $total = $query->count();

        $list = [];
        if ($total > 0) {
            $query1 = Db::name('lt')
                ->alias('l')
                ->join('ltcate c', 'l.ltcate_id = c.id', 'LEFT')
                ->field('l.id,l.title,l.content,l.view,l.ltcate_id,l.is_top,l.createtime,c.title as cate_title');

            // 分类筛选
            if ($ltcateId > 0) {
                $query1->where('l.ltcate_id', $ltcateId);
            }

            // 关键词搜索
            if (!empty($keyword)) {
                $query1->where('l.title|l.content', 'like', '%' . $keyword . '%');
            }
            $list = $query1
                ->order(['l.is_top' => 'desc', 'l.id' => 'desc'])
                ->page($page, $limit)
                ->select();

            // 处理文章内容截取和时间格式化
            foreach ($list as &$item) {

                if(strlen(strip_tags($item['content'])) > 180) {
                    $item['content'] = mb_substr(strip_tags($item['content']), 0, 180, 'utf-8') . '...';
                }else{
                    $item['content'] = strip_tags($item['content']);

                }
                 $item['createtime'] = date('Y-m-d H:i:s', $item['createtime']);
            }
            unset($item);
        }

        return json([
            'code' => 1,
            'data' => [
                'total' => $total,
                'list' => $list,
                'page' => $page,
                'pageSize' => $limit,
                'pages' => (int)ceil($total / $limit ?: 1)
            ]
        ]);
    }

    /**
     * 获取论坛文章详情API
     */
    public function lt_detail_api()
    {
        $id = (int)$this->request->get('id', 0);
        if ($id <= 0) {
            return json(['code' => 0, 'msg' => '参数错误']);
        }

        $detail = Db::name('lt')
            ->alias('l')
            ->join('ltcate c', 'l.ltcate_id = c.id', 'LEFT')
            ->field('l.id,l.title,l.content,l.view,l.ltcate_id,l.createtime,l.updatetime,c.title as cate_title')
            ->where('l.id', $id)
            ->find();

        if (empty($detail)) {
            return json(['code' => 0, 'msg' => '文章不存在']);
        }

        // 增加浏览量
        Db::name('lt')->where('id', $id)->setInc('view');

        // 格式化时间
        $detail['createtime'] = date('Y-m-d H:i:s', $detail['createtime']);
        $detail['updatetime'] = date('Y-m-d H:i:s', $detail['updatetime']);

        return json(['code' => 1, 'data' => $detail]);
    }

    public function video_detail()
    {
        $id = input('id');
        $info = Db::name('video')->where('id', '=', $id)->find();

        $map['id'] = $info['cate_id'];
        $fields = 'image,sub_name,rules,content1,content2,content3,content4,content5,content6';

        $data = Db::name('cate')->field($fields)->where($map)->find();
        if (!empty($data['image'])) {
            $data['image'] = config('http_url') . $data['image'];
        }
        $this->view->assign("image", $data['image'] ?? '');
        $this->view->assign("acName", $data['rules']);
        $this->view->assign("subName", $data['sub_name'] ?? '');

        $this->view->assign("info", $info);
        return $this->view->fetch();

    }
}
